<?php

namespace plugin\admin\app\controller\common;

use plugin\admin\app\controller\Base;
use support\Request;

class Logs extends Base
{
    /**
     * 获取类型日志
     * @return \support\Response
     */
    public function infos(Request $request){
        $type = $request->get('type');
        $typeArr = ['info','error'];
        if(!in_array($type,$typeArr)){
            abort(1001,'操作失败，请确认类型');
        }
        return $this->logList('/logs/admin/' . $type);
    }


    /**
     * 【重要接口】下载日志,仅限于logs文件夹下
     * @param $path
     * @param $name
     * @return \support\Response|\Webman\Http\Response
     */
    public function dowmload(Request $request){
        $data = $request->get();
        if(!$data['path'] || !$data['name']){
            abort(1001,'操作失败，无法下载');
        }
        $data['path'] = urldecode($data['path']);
        $data['name'] = urldecode($data['name']);
        $path = runtime_path() . '/logs/' . $data['path']. "/" . $data['name'];
        if(str_contains($data['path'],'.') || !file_exists($path)){
            abort(1001,'操作失败，无法下载');
        }
        return response()->download($path,$data['name']);
    }

    /**
     * 根据路径，查询日志文件目录，转换成列表
     * @param $path
     * @return \support\Response
     * @throws \support\exception\BusinessException
     */
    protected function logList($path = ''){
        $path = runtime_path() . $path;
        $arrFiles = [];
        $iterator = new \FilesystemIterator($path);
        if(!$iterator){
            abort(1001,'请求失败，文件路径错误');
        }
        foreach($iterator as $entry) {
            $arr = [];
            $arr['name'] = $entry->getFilename();
            $arr['getSize'] = $this->formatSize($entry->getSize());
            $arr['getMTime'] = date("Y-m-d H:i",$entry->getMTime()) ;
            $arrFiles[] = $arr;
        }
        return $this->json(0,'请求成功',$arrFiles);
    }

    protected function formatSize($file_size) {
        $size = sprintf("%u", $file_size);
        if($size == 0) {
            return("0 Bytes");
        }
        $sizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
        return round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizename[$i];
    }
}